package com.skyline.energy.definition;

import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.skyline.energy.annotation.ShardBy;
import com.skyline.energy.exception.DaoGenerateException;
import com.skyline.energy.utils.CommonUtils;

public class ShardDefinition {
	private String shardTable;
	private String shardParamName;
	private Integer shardParamIndex;
	private Method shardGetter;
	
	public Integer getShardParamIndex() {
		return shardParamIndex;
	}

	public Method getShardGetter() {
		return shardGetter;
	}
	
	public String getShardParamName() {
		return shardParamName;
	}
	
	public String getShardTable() {
		return shardTable;
	}
	
	protected void parseShardBy(Method method, Map<String, Integer> paramIndexes, Class<?>[] paramTypes) throws DaoGenerateException {
		ShardBy shardBy = method.getAnnotation(ShardBy.class);
		if(shardBy != null) {
			shardTable = shardBy.table();
			shardParamName = StringUtils.trimToEmpty(shardBy.param());
			
			int pos = shardParamName.indexOf('.');
			if (pos != -1) {
				String actualName = shardParamName.substring(0, pos);

				int index = CommonUtils.getParameIndex(paramIndexes, actualName);

				String prop = shardParamName.substring(pos + 1);
				Method getter = CommonUtils.findGetterByPropertyName(paramTypes[index], prop);
				
				this.shardGetter = getter;
				this.shardParamIndex = index;
			} else {
				this.shardParamIndex = CommonUtils.getParameIndex(paramIndexes, shardParamName);
			}
		}
		
	}
}
